/*
 * @Author: Zhang Kai
 * @Date: 2021-12-15 15:15:24
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-06 14:52:43
 * @FilePath: /metricsx-standard-ui/src/views/indexManage/dimension/index.tsx
 */
import { useStore } from '@/store';
import {
  defineComponent,
  computed,
  watch,
  ref,
  PropType,
  reactive,
  onMounted
} from 'vue';
import SearchForm from './components/SearchForm';
import Table from '@/components/Table/index';
import { ECustomColumn } from '@/utils/constants';
import './style/index.scss';
import CreateForm from './components/createForm';
import { rebuildObject } from '@/utils/util';
import { ElMessage, ElMessageBox } from 'element-plus/lib/index';
import BatchOperates from '@/components/batchOperates/index.vue';
import { useRoute } from 'vue-router';
import CustomColumn from '@/components/CustomColumn/index';
import GroupTree from '@/components/GroupTree';
import shrinkLeft from '@/assets/images/shrinkLeft.svg';
import activeShrinkLeft from '@/assets/images/activeShrinLeft.svg';
import Bulk from '@/components/Bulk/index';
import API from '@/services';
import _ from 'lodash';

const dimension = defineComponent({
  name: 'Dimension',
  components: { BatchOperates },
  setup(props, { slots, attrs, emit }) {
    // 获取api
    const {
      dimension: {
        getDimensionGroupRoot,
        deleteDimensionGroupById,
        putDimensionGroup,
        postDimensionGroup
      }
    } = API;
    // 选择row
    const multipleSelection: any = reactive({ data: [] });
    /* table List */
    const dimensionList: any = reactive({
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      order: undefined,
      sortBy: undefined
    });

    /* table loading */
    const TableLoading = ref(false);

    const formQuery = reactive({ form: { groupId: void 0 } });

    const store = useStore();

    const route = useRoute();

    const shrinkIcon = ref(shrinkLeft);

    // 分组key
    const groupKey = ref(1);

    /* 抽屉开关 */
    const visible = computed(() => store.state.dimension.drawerVisible);

    /* 编辑状态 */
    const isEdit = ref(false);

    /* 主题list */
    const subjectList = ref();

    /* 维度类型 */
    const dimensionTypeList = ref();

    /* 编辑信息 */
    const editingData = ref();

    /* 抽屉form ref */
    const formRef = ref();

    /* 名称重复字段及文案 */
    const errorData = ref([]);

    /* 下载模版Url */
    const downloadUrl = ref('');

    /* 收缩状态 */
    const toggle = ref(false);

    const tableColumn: any = ref([
      {
        keys: 1,
        sortable: true
      },
      {
        keys: 8,
        sortable: true
      },
      {
        label: '操作',
        keys: 10,
        default: ({ row }: any) => (
          <>
            <el-button type="text" onClick={() => edit(row?.id)}>
              编辑
            </el-button>
            <el-button
              type="text"
              onClick={() => onDelete(row.id)}
              disabled={!row.deletable}
            >
              删除
            </el-button>
          </>
        )
      }
    ]);

    const newTableColumn: any = ref([]);

    const settings: any = ref([]);

    //编辑
    const edit = async (id: any) => {
      try {
        const { code, data } = await API.dimension.getDimensionById({
          id
        });
        if (code === 200) {
          editingData.value = data;
        }
      } catch (error) {
        console.log(error);
      }
      isEdit.value = true;
      store.commit('dimension/toggleDrawerVisible', true);
    };

    /* 删除 */
    const onDelete = async (id: number) => {
      ElMessageBox.alert('', '是否确认删除该维度?', {
        confirmButtonText: '确认删除',
        showCancelButton: true,
        confirmButtonClass: 'message-box-del'
      }).then(async () => {
        try {
          const { code } = await API.dimension.deleteDimensionById({
            id
          });
          if (code === 200) {
            ElMessage.success('删除成功');
            queryDimensionList();
            groupKey.value++;
          }
        } catch (error) {
          ElMessage.error('删除失败');
          console.log(error);
        }
      });
    };

    /* 主题 */
    const querySubjectList = async () => {
      try {
        const { code, data } = await API.subject.getSubjectsFirstLevel();
        if (code === 200 && Array.isArray(data)) {
          subjectList.value = [...data];
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 维度类型枚举接口 */
    const getDimensionTypeList = async () => {
      try {
        const { code, data } = await API.enumBao.getDimensionType();
        if (code === 200 && Array.isArray(data)) {
          dimensionTypeList.value = [...data];
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* table list */
    const queryDimensionList = async (form?: any) => {
      try {
        TableLoading.value = true;
        const { pageNum, pageSize, order, sortBy } = dimensionList;
        const { code, data, msg } = await API.dimension.postDimensionList({
          pageNum,
          pageSize,
          order,
          sortBy,
          ...rebuildObject(formQuery.form)
        });
        if (code === 200 && Array.isArray(data?.list)) {
          dimensionList.list = data?.list;
          dimensionList.total = data?.total;
        }
      } catch (error) {
        console.log(error);
      } finally {
        TableLoading.value = false;
      }
    };

    /* 面包屑 抽屉关闭 */
    const handleClose = () => {
      store.commit('dimension/toggleDrawerVisible', false);
      editingData.value = '';
      errorData.value = [];
    };

    /* 提交 */
    const confirm = (form: any) => {
      formRef.value.validate(async (bol: Boolean) => {
        if (!bol) return;
        if (editingData.value?.id) {
          try {
            const groupId = form?.groupId;
            const { code, data }: any = await API.dimension.putDimensionById(
              { id: editingData.value?.id },
              {
                ...form,
                groupId: groupId.length ? groupId[groupId.length - 1] : groupId
              }
            );
            if (code === 200) {
              ElMessage.success('编辑成功');
              queryDimensionList();
              handleClose();
              groupKey.value++;
            } else {
              errorData.value = data;
            }
          } catch (error) {
            console.log(error);
          }
        } else {
          try {
            const { code, data }: any = await API.dimension.postDimension(form);
            if (code === 200) {
              ElMessage.success('创建成功');
              queryDimensionList();
              handleClose();
              groupKey.value++;
            } else {
              errorData.value = data;
            }
          } catch (error) {
            console.log(error);
          }
        }
      });
    };

    onMounted(() => {
      getCustomColumnApi();
      queryDimensionList();
      getDimensionTypeList();
      querySubjectList();
      if (route.query.modal) {
        store.commit('dimension/toggleDrawerVisible', true);
      }
    });

    const handleSelectionChange = (v: any) => {
      multipleSelection.data = v;
    };

    const handleBatchOperate = async (v: any) => {
      const ids: any = multipleSelection?.data
        ?.filter((v: any) => v.deletable)
        .map((d: any) => d.id);
      switch (v) {
        case 'delete':
          if (!ids.length) {
            ElMessage.warning('批量删除失败');
            return;
          }
          TableLoading.value = true;
          ElMessageBox.alert('', '是否确认删除已选维度?', {
            confirmButtonText: '确认删除',
            showCancelButton: true,
            confirmButtonClass: 'message-box-del'
          })
            .then(async () => {
              try {
                const { code, data, msg } =
                  await API.dimension.postDimensionBatchDelete(ids);
                if (code === 200) {
                  ElMessage.success('批量删除成功');
                  groupKey.value++;
                }
                dimensionList.pageNum = 1;
                queryDimensionList();
              } catch (error) {
                console.log(error);
              }
            })
            .catch(() => {
              ElMessage.info('批量取消删除');
            });
          TableLoading.value = false;
          break;
      }
    };

    /* 获取自定义列列表 */
    const getCustomColumnApi = async () => {
      try {
        const { code, data }: any = await API.userPageSetting.getFindOne({
          pageCode: ECustomColumn?.dimensionmgmt
        });
        if (code === 200) {
          settings.value = data?.settings;
          const column = data?.settings?.map((v: any, i: number) => {
            const columnIndex = tableColumn.value?.findIndex(
              (val: any) => val?.keys === v?.keys
            );
            return {
              ...tableColumn.value[columnIndex],
              ...v,
              columnKey: Date.now()
            };
          });
          column.unshift({
            type: 'selection',
            width: '55',
            isCheck: true
          });
          newTableColumn.value = _.compact(column);
        }
      } catch (error) {
        console.log(error);
      }
    };

    // 排序
    const sortTable = (obj: any) => {
      if (obj.prop) {
        const order = obj.order === 'ascending' ? 1 : 2;
        dimensionList.sortBy = obj.prop;
        dimensionList.order = order;
      } else {
        dimensionList.sortBy = undefined;
        dimensionList.order = undefined;
      }
      queryDimensionList();
    };

    /* 保存自定义列表 */
    const customColumnConfirm = async (vo: any) => {
      try {
        const { code } = await API.userPageSetting.postSave({
          pageCode: ECustomColumn?.dimensionmgmt,
          settings: vo?.map(({ disabled, keys, isCheck, label, prop }: any) => {
            return {
              disabled,
              keys,
              isCheck,
              label,
              prop
            };
          })
        });
        if (code === 200) {
          ElMessage.success('保存配置成功');
          getCustomColumnApi();
        }
      } catch (error) {
        console.log(error);
      }
    };

    return () => {
      return (
        <div class="dimension_container">
          <div
            class="dimension_container-left"
            style={{ width: toggle.value ? '0px' : '210px' }}
          >
            <img
              class={toggle.value && 'shrinkRight'}
              onClick={() => (toggle.value = !toggle.value)}
              src={shrinkIcon.value}
              onMouseenter={() => (shrinkIcon.value = activeShrinkLeft)}
              onMouseout={() => (shrinkIcon.value = shrinkLeft)}
              alt=""
            />
            <GroupTree
              titles="维度分组管理"
              groupKey={groupKey.value}
              listFn={getDimensionGroupRoot}
              delFn={deleteDimensionGroupById}
              reNameFn={putDimensionGroup}
              addFn={postDimensionGroup}
              onGetTreeNode={({ id }: any) => {
                if (id === 'new') return;
                formQuery.form.groupId = id;
                queryDimensionList();
              }}
            ></GroupTree>
          </div>
          <div class="dimension_container-right">
            <SearchForm
              onSearch={(form: any) => {
                dimensionList.pageNum = 1;
                dimensionList.pageSize = 10;
                formQuery.form = form;
                formQuery.form.groupId = void 0;
                queryDimensionList();
              }}
              subjectList={subjectList.value}
              dimensionTypeList={dimensionTypeList.value}
            />
            <div class="table-operate">
              <div class="CustomColumn-operate-wrap">
                <CustomColumn
                  onConfirm={(v: any) => customColumnConfirm(v)}
                  tableColumn={settings.value}
                />
                <div class="checkLength">
                  已选择<b>{multipleSelection.data.length}</b>个维度
                </div>
              </div>
              <div class="batch-operate-wrap">
                <Bulk
                  downloadList={[{ command: 'dimention', text: '维度下载' }]}
                  onCommand={() => {
                    downloadUrl.value = '/tmplate/download/';
                  }}
                  downloadUrl={downloadUrl.value}
                  tmpCode={'3'}
                  onSuccess={() => {
                    queryDimensionList();
                    groupKey.value++;
                  }}
                />
                <BatchOperates
                  v-loading={TableLoading.value}
                  opKeys={['delete']}
                  onBatchOperate={handleBatchOperate}
                  disabled={multipleSelection.data.length === 0}
                />
              </div>
            </div>
            <Table
              onSelectionChange={handleSelectionChange}
              v-loading={TableLoading.value}
              data={dimensionList.list}
              column={newTableColumn.value.filter((v: any) => v.isCheck)}
              onSortChange={sortTable}
              onPageCurrentChange={(page: number) => {
                dimensionList.pageNum = page;
                queryDimensionList();
              }}
              onPageSizeChange={(size: number) => {
                dimensionList.pageNum = 1;
                dimensionList.pageSize = size;
                queryDimensionList();
              }}
              pagination={{
                total: dimensionList.total * 1,
                currentPage: dimensionList.pageNum,
                pageSize: dimensionList.pageSize
              }}
            />

            <el-drawer
              custom-class="dimension-drawer"
              v-model={visible.value}
              title={isEdit.value ? '编辑维度' : '创建维度'}
              close-on-click-modal={false}
              append-to-body={true}
              direction="rtl"
              before-close={handleClose}
              onClosed={() => (isEdit.value = false)}
              lock-scroll={false}
            >
              {visible.value && (
                <CreateForm
                  formRef={formRef}
                  editingData={editingData.value}
                  isEdit={isEdit.value}
                  subjectList={subjectList.value}
                  dimensionTypeList={dimensionTypeList.value}
                  errorData={errorData.value}
                  onCancel={handleClose}
                  onConfirm={confirm}
                />
              )}
            </el-drawer>
          </div>
        </div>
      );
    };
  }
});
export default dimension;
